package com.binhthuan.catechist.server.bus;

import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.binhthuan.catechist.server.domain.Year;
import com.binhthuan.catechist.server.util.HibernateUtil;

public class YearBUS extends AbstractBUS {

    /**
     * Lấy năm học tương ứng của 1 ngày cho trước.
     * @param day Ngày cần biết thuộc năm học nào.
     * @return
     */
    public Year getSchoolYearByDate(Date day) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Year result = null;
        try{
            transaction = session.beginTransaction();
            Query query = session.createQuery("from Year y where y.startDay <= :day && :day <= y.endDay");
            query.setDate("day", day);
            result = (Year) query.uniqueResult();
            
            transaction.commit();
        } catch (HibernateException he) {
            he.printStackTrace();
            transaction.rollback();
        } finally {
            session.close();
        }
        
        return result;
    }

    public Year getSchoolYearByCourse(int courseId) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Year result = null;
        try{
            transaction = session.beginTransaction();
            Query query = session.createQuery("select c.year from Course c where c.id = :id");
            query.setInteger("id", courseId);
            result = (Year) query.uniqueResult();
            
            transaction.commit();
        } catch (HibernateException he) {
            he.printStackTrace();
            transaction.rollback();
        } finally {
            session.close();
        }
        
        return result;
    }

    public List<Year> getAllSchoolYears() {
        return getAll(Year.class);
    }

    public Year getSchoolYearById(int yearId) {
        return (Year) get(Year.class, yearId);
    }

    public boolean checkSchoolYearIsInUsed(int id) {
        return true;
    }

    public boolean deleteSchoolYear(int id) {
        return delete(Year.class, id);
    }
}
